/*
 * 
 * Copyright 2006 POB-Technology. All rights reserved.
 * POB-Technology PROPRIETARY/CONFIDENTIAL.
 * 
 */
#include <pob-eye.h>

/* This code works for the bluetooth Parani-ESD100/110/200/210 module.
 *
 * if you work with this module :
 *  - flash POB-EYE with the rgbbluetooth project
 *  - turn off POB-EYE
 *  - turn on bluetooth module and reset bluetooth module to factory default
 *  - set POB-EYE in running mode and turn on POB-EYE
 *
 */

static void SendATCommand(char *);
static int ReceiveATCommand(char *);

int InitBluetooth(void)
{
	char buffer[1024] ;

	//connect the POBEYE to the bluetooth module with default module parameter
	InitUART((UInt16)(BR_9600|NO_PARITY|ONE_STOP_BIT|LENGTH_8_BIT));

	//verify correct UART parameter
	SendATCommand("AT");

	ReceiveATCommand(buffer);
	if( buffer[0] != 'O' && buffer[1] != 'K' )
	{
		return -1 ;
	}


	//set serial setting to the bluetooth module
	SendATCommand("AT+UARTCONFIG,115200,N,1,0" );

	ReceiveATCommand(buffer);
	

	//set bluetooth module to Mode3 (slave mode, waiting connection)
	SendATCommand( "AT+BTMODE,3");

	ReceiveATCommand(buffer);

	//set bluetooth module name
	SendATCommand("AT+BTNAME=POBBOT");

	ReceiveATCommand(buffer);


	//reset bluetooth module
	SendATCommand("ATZ");

//	ReceiveATCommand(buffer);

	Wait(10000);

	//set POBEYE UART to default settings :
	InitUART((UInt16)(BR_115200|NO_PARITY|ONE_STOP_BIT|LENGTH_8_BIT));

	return 0 ;
}


void SendATCommand( char *command )
{
	int i = 0 ;

	//send command
	while( command[i] != 0 )
	{
		SendByteToUART( command[i] );

		i++ ;
	}

	//send cariage return
	SendByteToUART( 0x0D );

}

int ReceiveATCommand( char *command )
{
	int result = 0;
	int numberOfCr = 0;
	UInt8 rcv ;
	
	while(1)
	{
		rcv = GetByteFromUART();
		
		if( rcv != 0x0D && rcv != 0x0A )
		{
			command[result] = rcv ;
			result++ ;
		}
		else
			numberOfCr++ ;
		
		if( numberOfCr == 2 )
		{
			if( result != 0 )
				break ;
			else
				numberOfCr = 0;
		}
	}
	
	return result ;
}
